import pygame
import time
import queue
from web import mainThread
from player import SCREEN_WIDTH, SCREEN_HEIGHT, Music, MyTank, EnemyTank, Bullet

# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

# 定义背景色
BG_COLOR = BLACK
TEXT_COLOR = GREEN

# 当前用户状态, 文本列表， 其他, 公共消息队列, 发送消息的队列
system = [
    None,
    None,
    None,
    queue.Queue(),
    queue.Queue(),
]

# 初始化窗口
pygame.display.init()
# 设置窗口的大小及显示
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
# 设置窗口的标题
pygame.display.set_caption("坦克大战2.0")
# 关闭输入法
pygame.key.stop_text_input()
# 字体初始化
pygame.font.init()
font = pygame.font.SysFont("SimSun", 14)
# 初始化自己
my_tank = MyTank(screen, 180, 520)
# 初始化其他玩家
TankList = {}
enemyTankList = []
# 子弹列表
myBulletList = []
enemyBulletList = []


def blitMyBullet():  # 循环我方子弹列表, 并展示
    for myBullet in myBulletList:
        if myBullet.live:  # 判断子弹的状态
            myBullet.displayBullet()
            myBullet.move()
            myBullet.myBullet_hit_enemyTank()
            myBullet.hitWall()  # 检测我方坦克子弹是否碰撞
        else:
            myBulletList.remove(myBullet)


# def blitEnemyBullet():  # 循环敌方子弹列表, 并展示
#     for enemyBullet in enemyBulletList:
#         if enemyBullet.live:
#             enemyBullet.displayBullet()
#             enemyBullet.move()
#             enemyBullet.enemyBullet_hit_myTank()
#             enemyBullet.hitWall()  # 检测敌方坦克子弹是否碰撞
#         else:
#             enemyBulletList.remove(enemyBullet)


def messageShow(textlist=[]):
    """显示文本"""
    text_surfaces = [font.render(line, True, (0, 255, 0)) for line in textlist]
    text_positions = [
        (5, 400 + i * (text_surfaces[0].get_height() + 5))
        for i, _ in enumerate(textlist)
    ]
    for surface, pos in zip(text_surfaces, text_positions):
        screen.blit(surface, pos)


if __name__ == "__main__":
    # 启动网络线程
    thread1 = mainThread(system)
    thread1.start()
    isRun = True

    while isRun:
        time.sleep(0.1)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                isRun = False
            elif event.type == pygame.KEYUP:
                if system[0] == "wait" and event.key == pygame.K_1:
                    thread1.do_Send({"act": "ready"})
                    system[1] = None  # ["准备就绪,等待进入战场.", "1    准备就绪"]
                if system[0] == "ready" and event.key == pygame.K_1:
                    thread1.do_Send({"act": "wait"})
                    system[1] = None  # ["准备就绪,等待进入战场.", "1    取消准备"]
            elif event.type == pygame.KEYDOWN:
                if system[0] == "fight" and event.key == pygame.K_j:
                    if len(myBulletList) < 3:  # 可以同时发射子弹数量的上限
                        myBullet = Bullet(my_tank)
                        myBulletList.append(myBullet)
                        music = Music("img/fire.wav")
                        music.play()
        # 按住按键
        keys = pygame.key.get_pressed()
        if system[0] == "fight" and keys[pygame.K_w]:
            move, iz = True, 0
        elif system[0] == "fight" and keys[pygame.K_s]:
            move, iz = True, 180
        elif system[0] == "fight" and keys[pygame.K_a]:
            move, iz = True, 270
        elif system[0] == "fight" and keys[pygame.K_d]:
            move, iz = True, 90
        else:
            move = False
        if move:
            my_tank.roteMove(iz, 10)
            system[4].put(
                {
                    "act": "gens",
                    "guid": my_tank.guid,
                    "uid": None,
                    "role": None,
                    "group": my_tank.group,
                    "move": my_tank.move,
                    "look": my_tank.look,
                    "health": my_tank.health,
                    "status": my_tank.status,
                }
            )

        # 给窗口设置填充色
        screen.fill(BG_COLOR)
        # 绘制文本
        if system[1]:
            messageShow(system[1])
        # 显示自己
        my_tank.displayTank()
        # 更新玩家
        if not system[3].empty():
            msg = system[3].get()
            guid, status, move = msg.get("guid"), msg.get("status"), msg.get("move")

            if not TankList.get(guid):
                TankList[guid] = EnemyTank(
                    screen, move["ix"], move["iy"], move["speed"]
                )
            TankList[guid].guid = guid
            TankList[guid].status = status
            TankList[guid].health = msg.get("health")
            TankList[guid].move = msg.get("move")
            TankList[guid].look = msg.get("look")
            TankList[guid].setGroup(msg.get("group"))
            TankList[guid].pointMove()

            # find = 0
            # for tank in enemyTankList:
            #     if tank.guid == guid:
            #         find = 1
            #         tank.status = status
            #         tank.health = msg.get("health")
            #         tank.move = msg.get("move")
            #         tank.look = msg.get("look")
            #         tank.setGroup(msg.get("group"))
            #         tank.pointMove()

        # 显示玩家
        for guid, tank in TankList.items():
            if not tank.group:
                tank.roteMove()
            tank.displayTank()
        # 显示我方坦克子弹
        # blitMyBullet()
        # 显示敌方子弹
        # blitEnemyBullet()
        pygame.display.update()

    pygame.quit()
    thread1.stop()
    thread1.join()
    print("...Bye...")
